<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import sider from './HrSider.vue'
import heade from './HrHeader.vue'
// API基础URL（根据实际情况修改）
import {gethrlist, recordHrOperation, addEmployee as addEmployeeApi, deleteEmployee as deleteEmployeeApi, updateEmployee as updateEmployeeApi, batchUpdateEmployees as batchUpdateEmployeesApi, batchDeleteEmployees as batchDeleteEmployeesApi} from '@/api/hr.js'
import {useUserStore} from '@/stores/index.js'
// 状态管理
const loading = ref(false)
const error = ref('')
const employees = reactive([])
const userStore = useUserStore()
// UI状态（保持不变）
const searchQuery = ref('')
const departmentFilter = ref('all')
const isBatchMode = ref(false)
const selectedEmployeeIds = ref([])
const isBatchEditModalVisible = ref(false)
const isDetailModalVisible = ref(false)
const isEditModalVisible = ref(false)
const isNewEmployeeModalVisible = ref(false)
const currentViewEmployee = ref(null)
const activeDropdown = ref(null)
// API函数
// 记录操作日志
const recordOperationLog = async (userId, operatorId, operationType, fieldChanges = []) => {
  try {
    // 为每个字段变更创建单独的日志记录
    const logPromises = fieldChanges.map(change => {
      const logData = {
        user_id: userId,  // 被操作人的用户ID
        operator_id: operatorId,  // 操作人的用户ID
        operation_type: operationType,  // 操作类型：增、删、改
        operation_field: change.field,  // 被修改的字段名
        old_value: change.oldValue || '',  // 旧值
        new_value: change.newValue || '',  // 新值
        operation_time: new Date().toISOString(),  // 操作时间
        operation_ip: '',  // IP地址（前端无法获取，由后端填充）
        remark: change.remark || ''  // 备注
      }
      return recordHrOperation(logData)
    })
    
    await Promise.all(logPromises)
    console.log('操作日志记录成功')
  } catch (err) {
    console.error('记录操作日志失败:', err)
    // 日志记录失败不影响主要操作，只在控制台输出错误
  }
}

const fetchEmployees = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await gethrlist()

    // 根据实际API响应结构调整
    if (response.data.code === 1) {
      employees.splice(0, employees.length, ...response.data.data)
    } else {
      throw new Error(response.data.msg || '获取员工数据失败')
    }
  } catch (err) {
    error.value = err.message || '获取员工数据失败'
    console.error('获取员工数据失败:', err)
  } finally {
    loading.value = false
  }
}
const createEmployee = async (employeeData) => {
  loading.value = true
  try {
    const response = await addEmployeeApi(employeeData)
    if (response.data.code === 1) {
      // 将新员工添加到列表
      employees.unshift(response.data.data)
      return true
    } else {
      throw new Error(response.data.msg || '创建员工失败')
    }
  } catch (err) {
    error.value = err.message || '创建员工失败'
    console.error('创建员工失败:', err)
    return false
  } finally {
    loading.value = false
  }
}
const updateEmployee = async (employeeData) => {
  loading.value = true
  try {
    const response = await updateEmployeeApi(employeeData, employeeData.userId)
    if (response.data.code === 1) {
      // 更新本地员工列表
      const index = employees.findIndex(emp => emp.userId === employeeData.userId)
      if (index !== -1) {
        Object.assign(employees[index], employeeData)
      }
      return true
    } else {
      throw new Error(response.data.msg || '更新员工失败')
    }
  } catch (err) {
    error.value = err.message || '更新员工失败'
    console.error('更新员工失败:', err)
    return false
  } finally {
    loading.value = false
  }
}
const deleteEmployeeById = async (userId) => {
  loading.value = true
  try {
    const response = await deleteEmployeeApi(userId)
    if (response.data.code === 1) {
      // 从本地列表中删除员工
      const index = employees.findIndex(emp => emp.userId === userId)
      if (index !== -1) {
        employees.splice(index, 1)
      }
      return true
    } else {
      throw new Error(response.data.msg || '删除员工失败')
    }
  } catch (err) {
    error.value = err.message || '删除员工失败'
    console.error('删除员工失败:', err)
    return false
  } finally {
    loading.value = false
  }
}
const batchUpdateEmployees = async (ids, updateData) => {
  loading.value = true
  try {
    const response = await batchUpdateEmployeesApi(ids, updateData)
    if (response.data.code === 1) {
      // 更新本地员工列表
      const updatedEmployees = response.data.data
      updatedEmployees.forEach(updated => {
        const index = employees.findIndex(emp => emp.userId === updated.userId)
        if (index !== -1) {
          Object.assign(employees[index], updated)
        }
      })
      return true
    } else {
      throw new Error(response.data.msg || '批量更新失败')
    }
  } catch (err) {
    error.value = err.message || '批量更新失败'
    console.error('批量更新失败:', err)
    return false
  } finally {
    loading.value = false
  }
}
const batchDeleteEmployeesByIds = async (ids) => {
  loading.value = true
  try {
    const response = await batchDeleteEmployeesApi(ids)
    if (response.data.code === 1) {
      // 从本地列表中删除
      for (let i = employees.length - 1; i >= 0; i--) {
        if (ids.includes(employees[i].userId)) {
          employees.splice(i, 1)
        }
      }
      return true
    } else {
      throw new Error(response.data.msg || '批量删除失败')
    }
  } catch (err) {
    error.value = err.message || '批量删除失败'
    console.error('批量删除失败:', err)
    return false
  } finally {
    loading.value = false
  }
}
// 初始化数据
onMounted(() => {
  fetchEmployees()
})
// 批量编辑表单
const batchEditForm = reactive({
  department: '',
  position: ''
})
// 编辑员工表单
const editForm = reactive({
  userId: '',
  username: '',
  department: '',
  role: '',
  authType: 1
})
// 新增员工表单
const newEmployeeForm = reactive({
  name: '',
  department: '技术部',
  position: '',
  email: '',
  phone: ''
})
// 计算属性：过滤后的员工列表
const filteredEmployees = computed(() => {
  let result = employees
  // 按部门筛选
  if (departmentFilter.value !== 'all') {
    result = result.filter(emp => emp.department === departmentFilter.value)
  }
  // 按搜索词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(emp =>
      emp.username.toLowerCase().includes(query) ||
      emp.userId.toString().includes(query)
    )
  }
  return result
})
// --- 函数定义 ---
// 生成新的工号（改为API调用或前端生成）
const generateNewEmployeeId = () => {
  if (employees.length === 0) return 'E001'
  
  // 过滤出有效的 employeeId，并提取数字部分
  const validIds = employees
    .filter(emp => emp.employeeId && typeof emp.employeeId === 'string' && emp.employeeId.startsWith('E'))
    .map(emp => parseInt(emp.employeeId.substring(1)))
    .filter(id => !isNaN(id))
  
  // 如果没有有效的工号，从 E001 开始
  if (validIds.length === 0) return 'E001'
  
  const maxId = Math.max(...validIds)
  return `E${String(maxId + 1).padStart(3, '0')}`
}
// 打开新增员工模态框
const openNewEmployeeModal = () => {
  Object.assign(newEmployeeForm, {
    name: '',
    department: '技术部',
    position: '',
    email: '',
    phone: ''
  })
  isNewEmployeeModalVisible.value = true
}
// 关闭新增员工模态框
const closeNewEmployeeModal = () => {
  isNewEmployeeModalVisible.value = false
}
// 确认新增员工（改为API调用）
const addNewEmployee = async () => {
  if (!newEmployeeForm.name) {
    alert('请填写员工姓名！')
    return
  }
  if (!newEmployeeForm.phone) {
    alert('请填写员工电话！')
    return
  }
  // 将前端表单字段映射到后端期望的字段（只发送数据库存在的字段）
  const employeeData = {
    username: newEmployeeForm.name,        // name -> username
    password: '123456',                    // 默认密码
    department: newEmployeeForm.department,
    role: newEmployeeForm.position || '员工',  // position -> role，提供默认值
    email: newEmployeeForm.email || '',
    phone: newEmployeeForm.phone,          // phone 必填，不提供默认值
    authType: 1  // 默认为普通员工
  }
  const success = await createEmployee(employeeData)
  if (success) {
    // 记录新增操作日志
    const newEmployee = employees[0] // 新增的员工在数组开头
    const fieldChanges = [
      { field: '姓名', oldValue: '', newValue: newEmployeeForm.name, remark: '新增员工' },
      { field: '部门', oldValue: '', newValue: newEmployeeForm.department, remark: '新增员工' },
      { field: '职务', oldValue: '', newValue: newEmployeeForm.position || '员工', remark: '新增员工' },
      { field: '邮箱', oldValue: '', newValue: newEmployeeForm.email || '', remark: '新增员工' },
      { field: '电话', oldValue: '', newValue: newEmployeeForm.phone, remark: '新增员工' }
    ]
    await recordOperationLog(
      newEmployee.userId,
      userStore.user.userId,
      '增',
      fieldChanges
    )
    closeNewEmployeeModal()
  }
}
// 查看员工详情（保持不变）
const viewEmployeeDetail = (employee) => {
  currentViewEmployee.value = employee
  isDetailModalVisible.value = true
}
// 切换下拉菜单（保持不变）
const toggleDropdown = (employeeId) => {
  activeDropdown.value = activeDropdown.value === employeeId ? null : employeeId
}
// 点击其他地方关闭下拉菜单（保持不变）
const closeDropdowns = () => {
  activeDropdown.value = null
}
// 编辑员工（保持不变）
const editEmployee = (employee) => {
  Object.assign(editForm, employee)
  isEditModalVisible.value = true
  closeDropdowns()
}
// 保存员工编辑（改为API调用）
const saveEmployeeEdit = async () => {
  // 查找原始员工数据以比较变化
  const originalEmployee = employees.find(emp => emp.userId === editForm.userId)
  const fieldChanges = []
  
  if (originalEmployee) {
    if (originalEmployee.username !== editForm.username) {
      fieldChanges.push({
        field: '姓名',
        oldValue: originalEmployee.username,
        newValue: editForm.username,
        remark: '修改员工信息'
      })
    }
    if (originalEmployee.department !== editForm.department) {
      fieldChanges.push({
        field: '部门',
        oldValue: originalEmployee.department,
        newValue: editForm.department,
        remark: '修改员工信息'
      })
    }
    if (originalEmployee.role !== editForm.role) {
      fieldChanges.push({
        field: '角色',
        oldValue: originalEmployee.role,
        newValue: editForm.role,
        remark: '修改员工信息'
      })
    }
    if (originalEmployee.authType !== editForm.authType) {
      const authTypeMap = { 1: '普通员工', 2: '审批经理', 3: '人事管理员', 4: '财务管理员' }
      fieldChanges.push({
        field: '权限等级',
        oldValue: authTypeMap[originalEmployee.authType] || originalEmployee.authType,
        newValue: authTypeMap[editForm.authType] || editForm.authType,
        remark: '修改员工信息'
      })
    }
  }
  
  const success = await updateEmployee(editForm)
  if (success) {
    // 记录修改操作日志
    if (fieldChanges.length > 0) {
      await recordOperationLog(
        editForm.userId,
        userStore.user.userId,
        '改',
        fieldChanges
      )
    }
    isEditModalVisible.value = false
  }
}
// 删除员工（改为API调用）
const deleteEmployee = async (employeeId, employeeName) => {
  if (confirm(`确定要删除员工 ${employeeName} 吗？此操作不可恢复！`)) {
    const success = await deleteEmployeeById(employeeId)
    if (success) {
      // 记录删除操作日志
      const fieldChanges = [{
        field: '员工记录',
        oldValue: employeeName,
        newValue: '',
        remark: '删除员工'
      }]
      await recordOperationLog(
        employeeId,
        userStore.user.userId,
        '删',
        fieldChanges
      )
    }
    closeDropdowns()
  }
}
// 切换批量管理模式（保持不变）
const toggleBatchMode = () => {
  isBatchMode.value = !isBatchMode.value
  selectedEmployeeIds.value = []
  closeDropdowns()
}
// 全选/取消全选
const handleSelectAll = () => {
  if (selectedEmployeeIds.value.length === filteredEmployees.value.length) {
    selectedEmployeeIds.value = []
  } else {
    selectedEmployeeIds.value = filteredEmployees.value.map(emp => emp.userId)
  }
}
// 切换单个员工选中状态（保持不变）
const toggleEmployeeSelection = (employeeId) => {
  const index = selectedEmployeeIds.value.indexOf(employeeId)
  if (index > -1) {
    selectedEmployeeIds.value.splice(index, 1)
  } else {
    selectedEmployeeIds.value.push(employeeId)
  }
}
// 打开批量编辑模态框（保持不变）
const openBatchEditModal = () => {
  isBatchEditModalVisible.value = true
  batchEditForm.department = ''
  batchEditForm.position = ''
}
// 确认批量编辑（改为API调用）
const confirmBatchEdit = async () => {
  const updateData = {}
  if (batchEditForm.department) {
    updateData.department = batchEditForm.department
  }
  if (batchEditForm.position) {
    updateData.position = batchEditForm.position
  }
  const success = await batchUpdateEmployees(selectedEmployeeIds.value, updateData)
  if (success) {
    // 记录批量修改操作日志
    const selectedEmployees = employees.filter(emp => selectedEmployeeIds.value.includes(emp.userId))
    for (const emp of selectedEmployees) {
      const fieldChanges = []
      if (batchEditForm.department) {
        fieldChanges.push({
          field: '部门',
          oldValue: emp.department,
          newValue: batchEditForm.department,
          remark: '批量修改'
        })
      }
      if (batchEditForm.position) {
        fieldChanges.push({
          field: '职务',
          oldValue: emp.role,
          newValue: batchEditForm.position,
          remark: '批量修改'
        })
      }
      await recordOperationLog(
        emp.userId,
        userStore.user.userId,
        '改',
        fieldChanges
      )
    }
    isBatchEditModalVisible.value = false
    selectedEmployeeIds.value = []
    toggleBatchMode()
  }
}
// 批量删除（改为API调用）
const batchDelete = async () => {
  if (selectedEmployeeIds.value.length === 0) return
  if (confirm(`确定要删除选中的 ${selectedEmployeeIds.value.length} 名员工吗？此操作不可恢复！`)) {
    // 记录被删除员工的姓名
    const selectedEmployees = employees.filter(emp => selectedEmployeeIds.value.includes(emp.userId))
    const success = await batchDeleteEmployeesByIds(selectedEmployeeIds.value)
    if (success) {
      // 记录批量删除操作日志
      for (const emp of selectedEmployees) {
        const fieldChanges = [{
          field: '员工记录',
          oldValue: emp.username,
          newValue: '',
          remark: '批量删除员工'
        }]
        await recordOperationLog(
          emp.userId,
          userStore.user.userId,
          '删',
          fieldChanges
        )
      }
      selectedEmployeeIds.value = []
      toggleBatchMode()
    }
  }
}
</script>
<template>
  <div class="admin-layout" @click="closeDropdowns">
    <!-- 顶栏 -->
    <div class = topbar>
      <heade/>
    </div>
    <!-- 侧边栏 -->
    <div class = sidebar>
      <div class = sidebar-menu>
        <sider/>
      </div>
    </div>
    <!-- 主内容区容器 -->
    <div class="content-wrapper">
      <div class="main-content">
        <div class="content-section">
          <div class="section-header">
            <h3>人事管理</h3>
            <div class="header-actions">
              <div class="filter-buttons">
                <!-- 新增员工按钮 -->
                <button class="filter-btn add-btn" @click="openNewEmployeeModal">
                  + 新增员工
                </button>
                <!-- 刷新按钮 -->
                <button class="filter-btn" @click="fetchEmployees" :disabled="loading">
                  {{ loading ? '加载中...' : '刷新' }}
                </button>
                <!-- 批量管理按钮 -->
                <button class="filter-btn" :class="{ active: isBatchMode }" @click="toggleBatchMode">
                  {{ isBatchMode ? '退出批量' : '批量管理' }}
                </button>
                <!-- 批量操作按钮 -->
                <template v-if="isBatchMode && selectedEmployeeIds.length > 0">
                  <button class="filter-btn batch-btn edit-btn" @click="openBatchEditModal">
                    编辑 ({{ selectedEmployeeIds.length }})
                  </button>
                  <button class="filter-btn batch-btn delete-btn" @click="batchDelete">
                    删除 ({{ selectedEmployeeIds.length }})
                  </button>
                </template>
                <!-- 全选框 -->
                <label v-if="isBatchMode" class="select-all-label">
                  <input
                    type="checkbox"
                    :checked="selectedEmployeeIds.length === filteredEmployees.length && filteredEmployees.length > 0"
                    @change="handleSelectAll"
                  >
                  全选
                </label>
                <!-- 部门筛选 -->
                <select v-model="departmentFilter" class="dept-select">
                  <option value="all">全部部门</option>
                  <option value="技术部">技术部</option>
                  <option value="市场部">市场部</option>
                  <option value="财务部">财务部</option>
                  <option value="人事部">人事部</option>
                </select>
                <!-- 搜索框 -->
                <el-input v-model="searchQuery" style="width: 240px;" placeholder="搜索姓名或用户ID" />
              </div>
            </div>
          </div>
          <!-- 错误提示 -->
          <div v-if="error" class="error-message">
            {{ error }}
            <button @click="error = ''" class="close-error">×</button>
          </div>
          <!-- 员工列表 - 占满宽度 -->
          <div class="employees-full-list">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-state">
              <div class="loading-spinner"></div>
              <p>加载中...</p>
            </div>
            <!-- 空状态 -->
            <div v-else-if="filteredEmployees.length === 0" class="empty-state">
              <div class="empty-icon">🔍</div>
              <p>没有找到匹配的员工</p>
            </div>
            <!-- 表格视图 -->
            <div v-else class="employee-table">
              <table>
                <thead>
                <tr>
                  <th v-if="isBatchMode" width="50">选择</th>
                  <th width="100">用户ID</th>
                  <th width="150">姓名</th>
                  <th width="150">部门</th>
                  <th width="200">角色</th>
                  <th width="100">权限等级</th>
                  <th width="200">操作</th>
                </tr>
                </thead>
                <tbody>
                <tr
                  v-for="employee in filteredEmployees"
                  :key="employee.userId"
                  :class="{ 'selected': selectedEmployeeIds.includes(employee.userId) }"
                >
                  <!-- 批量选择框 -->
                  <td v-if="isBatchMode">
                    <input
                      type="checkbox"
                      :checked="selectedEmployeeIds.includes(employee.userId)"
                      @change="toggleEmployeeSelection(employee.userId)"
                    >
                  </td>
                  <td><span class="employee-id">{{ employee.userId }}</span></td>
                  <td>{{ employee.username }}</td>
                  <td>{{ employee.department }}</td>
                  <td>{{ employee.role }}</td>
                  <td>
		                      <span class="auth-badge" :class="'auth-level-' + employee.authType">
		                        {{ employee.authType === 1 ? '普通员工' : employee.authType === 2 ? '审批经理' : employee.authType === 3 ? '人事管理员' : employee.authType === 4 ? '财务管理员' : '未知' }}
		                      </span>
                  </td>
                  <td @click.stop>
                    <div class="action-buttons">
                      <button class="action-btn view-btn" @click="viewEmployeeDetail(employee)">查看详情</button>
                      <div class="dropdown" @click.stop>
                        <button class="action-btn manage-btn" @click="toggleDropdown(employee.userId)">管理 ▼</button>
                        <div v-show="activeDropdown === employee.userId" class="dropdown-menu">
                          <button class="dropdown-item edit" @click="editEmployee(employee)">修改</button>
                          <button class="dropdown-item delete" @click="deleteEmployee(employee.userId, employee.username)">删除</button>
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增员工模态框 -->
    <div v-if="isNewEmployeeModalVisible" class="profile-modal" @click.self="closeNewEmployeeModal">
      <div class="profile-content">
        <div class="profile-header">
          <h3>新增员工</h3>
          <button class="close-btn" @click="closeNewEmployeeModal">×</button>
        </div>
        <div class="profile-body">
          <div class="detail-row">
            <label>姓名：<span style="color: red;">*</span></label>
            <input type="text" v-model="newEmployeeForm.name" required placeholder="请输入员工姓名">
          </div>
          <div class="detail-row">
            <label>部门：</label>
            <select v-model="newEmployeeForm.department">
              <option value="技术部">技术部</option>
              <option value="市场部">市场部</option>
              <option value="财务部">财务部</option>
              <option value="人事部">人事部</option>
            </select>
          </div>
          <div class="detail-row">
            <label>职务：</label>
            <input type="text" v-model="newEmployeeForm.position" placeholder="请输入职务（可选）">
          </div>
          <div class="detail-row">
            <label>邮箱：</label>
            <input type="email" v-model="newEmployeeForm.email" placeholder="请输入邮箱（可选）">
          </div>
          <div class="detail-row">
            <label>电话：<span style="color: red;">*</span></label>
            <input type="tel" v-model="newEmployeeForm.phone" required placeholder="请输入电话号码">
          </div>
          <div class="profile-actions">
            <button class="profile-btn save-btn" @click="addNewEmployee" :disabled="loading">
              {{ loading ? '保存中...' : '保存' }}
            </button>
            <button class="profile-btn" @click="closeNewEmployeeModal">取消</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 员工详情模态框 -->
    <div v-if="isDetailModalVisible" class="profile-modal" @click.self="isDetailModalVisible = false">
      <div class="profile-content">
        <div class="profile-header">
          <h3>员工详情</h3>
          <button class="close-btn" @click="isDetailModalVisible = false">×</button>
        </div>
        <div class="profile-body" v-if="currentViewEmployee">
          <div class="detail-row">
            <label>用户ID：</label>
            <span>{{ currentViewEmployee.userId }}</span>
          </div>
          <div class="detail-row">
            <label>姓名：</label>
            <span>{{ currentViewEmployee.username }}</span>
          </div>
          <div class="detail-row">
            <label>部门：</label>
            <span>{{ currentViewEmployee.department }}</span>
          </div>
          <div class="detail-row">
            <label>角色：</label>
            <span>{{ currentViewEmployee.role }}</span>
          </div>
          <div class="detail-row">
            <label>权限等级：</label>
            <span>{{ currentViewEmployee.authType === 1 ? '普通员工' : currentViewEmployee.authType === 2 ? '审批经理' : currentViewEmployee.authType === 3 ? '人事管理员' : currentViewEmployee.authType === 4 ? '财务管理员' : '未知' }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 编辑员工模态框 -->
    <div v-if="isEditModalVisible" class="profile-modal" @click.self="isEditModalVisible = false">
      <div class="profile-content">
        <div class="profile-header">
          <h3>编辑员工</h3>
          <button class="close-btn" @click="isEditModalVisible = false">×</button>
        </div>
        <div class="profile-body">
          <div class="detail-row">
            <label>用户ID：</label>
            <input type="text" v-model="editForm.userId" disabled>
          </div>
          <div class="detail-row">
            <label>姓名：</label>
            <input type="text" v-model="editForm.username">
          </div>
          <div class="detail-row">
            <label>部门：</label>
            <select v-model="editForm.department">
              <option value="技术部">技术部</option>
              <option value="市场部">市场部</option>
              <option value="财务部">财务部</option>
              <option value="人事资源部">人事资源部</option>
            </select>
          </div>
          <div class="detail-row">
            <label>角色：</label>
            <input type="text" v-model="editForm.role">
          </div>
          <div class="detail-row">
            <label>权限等级：</label>
            <select v-model="editForm.authType">
              <option :value="1">普通员工</option>
              <option :value="2">审批经理</option>
              <option :value="3">人事管理员</option>
              <option :value="4">财务管理员</option>
            </select>
          </div>
          <div class="profile-actions">
            <button class="profile-btn save-btn" @click="saveEmployeeEdit" :disabled="loading">
              {{ loading ? '保存中...' : '保存' }}
            </button>
            <button class="profile-btn" @click="isEditModalVisible = false">取消</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 批量编辑模态框 -->
    <div v-if="isBatchEditModalVisible" class="profile-modal" @click.self="isBatchEditModalVisible = false">
      <div class="profile-content">
        <div class="profile-header">
          <h3>批量编辑</h3>
          <button class="close-btn" @click="isBatchEditModalVisible = false">×</button>
        </div>
        <div class="profile-body">
          <div class="detail-row">
            <label>新部门：</label>
            <select v-model="batchEditForm.department">
              <option value="">请选择部门</option>
              <option value="技术部">技术部</option>
              <option value="市场部">市场部</option>
              <option value="财务部">财务部</option>
              <option value="人事部">人事部</option>
            </select>
          </div>
          <div class="detail-row">
            <label>新职务：</label>
            <input type="text" v-model="batchEditForm.position" placeholder="留空则不修改">
          </div>
          <div class="profile-actions">
            <button class="profile-btn save-btn" @click="confirmBatchEdit" :disabled="loading">
              {{ loading ? '处理中...' : '确认修改' }}
            </button>
            <button class="profile-btn" @click="isBatchEditModalVisible = false">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* --- 布局样式 --- */
.content-wrapper {
  flex: 1;
  margin-top: 50px;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.content-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  height: 100%;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px;
  border-bottom: 1px solid #e8e8e8;
}
.section-header h3 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #333;
}
/* --- 过滤按钮样式 --- */
.header-actions {
  display: flex;
  align-items: center;
}
.filter-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}
.filter-btn, .dept-select {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}
.filter-btn:hover, .dept-select:hover {
  border-color: #667eea;
}
.filter-btn.active {
  background: #667eea;
  border-color: #667eea;
  color: white;
}
.filter-btn.add-btn { /* 新增按钮样式 */
  background: #52c41a;
  color: white;
  border-color: #52c41a;
}
.filter-btn.add-btn:hover {
  background: #73d13d;
  border-color: #73d13d;
}
.filter-btn.edit-btn:hover { border-color: #1890ff; color: #1890ff; }
.filter-btn.delete-btn:hover { border-color: #ff4d4f; color: #ff4d4f; }
.select-all-label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}
/* --- 员工全宽列表样式 --- */
.employees-full-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}
.employee-table {
  width: 100%;
}
.employee-table table {
  width: 100%;
  border-collapse: collapse;
}
.employee-table th {
  background: #fafafa;
  padding: 12px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #e8e8e8;
}
.employee-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}
.employee-table tr:hover {
  background: #f8f9fa;
}
.employee-table tr.selected {
  background: #e8f4fd;
}
.employee-id {
  font-size: 12px;
  color: #999;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
}
.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}
.status-badge.active {
  background: #d4edda;
  color: #155724;
}
.status-badge.inactive {
  background: #fff3cd;
  color: #856404;
}
/* --- 权限等级样式 --- */
.auth-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}
.auth-badge.auth-level-1 {
  background: #e8f5e9;
  color: #2e7d32;
}
.auth-badge.auth-level-2 {
  background: #e3f2fd;
  color: #1565c0;
}
.auth-badge.auth-level-3 {
  background: #fff3e0;
  color: #e65100;
}
.auth-badge.auth-level-4 {
  background: #fce4ec;
  color: #c2185b;
}
/* --- 操作按钮样式 --- */
.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}
.action-btn {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}
.action-btn:hover {
  border-color: #667eea;
  color: #667eea;
}
.action-btn.view-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}
.action-btn.manage-btn {
  position: relative;
}
.dropdown {
  position: relative;
}
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  z-index: 10;
  min-width: 100px;
}
.dropdown-item {
  display: block;
  width: 100%;
  padding: 8px 12px;
  border: none;
  background: none;
  text-align: left;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}
.dropdown-item:hover {
  background: #f0f0f0;
}
.dropdown-item.edit:hover {
  color: #1890ff;
}
.dropdown-item.delete:hover {
  color: #ff4d4f;
}
/* --- 侧边栏和顶栏样式 --- */
.sidebar {
  width: 260px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-sizing: border-box;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
}
.admin-layout {
  display: flex;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
.sidebar-header { padding: 30px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.1); }
.sidebar-header h2 { margin: 0 0 5px 0; font-size: 20px; font-weight: 600; }
.sidebar-header p { margin: 0; font-size: 14px; opacity: 0.8; }
.sidebar-menu { flex: 1; padding: 20px 0; }
.menu-item { display: flex; align-items: center; padding: 15px 25px; cursor: pointer; transition: all 0.3s ease; border-left: 3px solid transparent; }
.menu-item:hover { background: rgba(255, 255, 255, 0.1); }
.menu-item.active { background: rgba(255, 255, 255, 0.2); border-left-color: white; }
.menu-icon { font-size: 20px; margin-right: 15px; width: 25px; text-align: center; }
.menu-text { font-size: 15px; font-weight: 500; }

.topbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 30px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 10;
}
/* --- 模态框样式 --- */
.profile-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.profile-content {
  background: #fff;
  padding: 0;
  border-radius: 12px;
  width: 500px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
  animation: modalFadeIn 0.3s ease-out;
}
@keyframes modalFadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}
.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #e8e8e8;
}
.profile-header h3 { margin: 0; font-size: 18px; color: #333; }
.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #aaa;
  cursor: pointer;
  line-height: 1;
  padding: 0;
  width: 30px;
  height: 30px;
}
.close-btn:hover { color: #333; }
.profile-body { padding: 30px; text-align: left; }
.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.detail-row label {
  width: 100px;
  font-weight: 500;
  color: #333;
  margin-right: 15px;
  flex-shrink: 0;
}
.detail-row span {
  color: #555;
}
.detail-row input, .detail-row select {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
}
.profile-actions {
  margin-top: 30px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.profile-btn {
  padding: 10px 20px;
  border: 1px solid #d9d9d9;
  background: #fff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}
.profile-btn:hover {
  background-color: #f5f5f5;
  border-color: #667eea;
  color: #667eea;
}
.profile-btn.save-btn {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}
.profile-btn.save-btn:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}
/* --- 空状态样式 --- */
.empty-state {
  padding: 60px;
  text-align: center;
  color: #999;
}
.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
}
</style>
